'''
coding:utf-8
@Software:PyCharm
@Time:2022/6/9 21:32
@Author:liuyi
'''
import os
import sys

import pandas as pd

# 用户基础数据
class User:
    user = None
    data = []

    def __init__(self):
        df = pd.read_csv("data/user.csv", sep="\t")
        # 转列表
        self.data = df.values.tolist()
        for i in self.data:
            i[1] = str(i[1])

    def __new__(cls, *args, **kwargs):
        if cls.user is None:
            cls.user = object.__new__(cls)
        return cls.user

    # 登录
    def login(self,username,password):
        for i in self.data:
            if username == i[0] and password == i[1]:
                print("登录成功")
                return True
        print("登录失败")
        return False


    # 注册
    def register(self,username,password,price):
        for i in self.data:
            if username == i[0]:
                print("用户已存在")
                return
        self.data.append([username,password,price])
        self.__user()

    # 返回用户余额
    def getPrice(self,username):
        for i in self.data:
            if i[0] == username:
                return i[2]

    # 购买商品后用来减少余额
    def setPrice(self,username,shopping_total_price):
        for i in self.data:
            if i[0] == username:
                i[2] = i[2] - shopping_total_price
                self.__user()

    # 数据持久化
    def __user(self):
        df = pd.DataFrame(self.data)
        df.to_csv("./data/user.csv",sep="\t",header=["用户名","密码","余额"],index=False)

# 用户购物车数据
class UserShoppingData:
    shopping_data = []

    def __init__(self,username):
        self.username = username
        fileList = os.listdir("./data")
        if f"{username}.csv" in fileList:
            df = pd.read_csv(f"./data/{username}.csv",sep="\t")
            self.shopping_data = df.values.tolist()

    # 添加购物车商品
    def addShoppingData(self,shopping_id,shopping_name,shopping_price,shopping_num,shopping_total_price):
        if self.shopping_data == []:
            count = [shopping_id,shopping_name,shopping_price,shopping_num,shopping_total_price]
            self.shopping_data.append(count)
            self.__shoppingData()
        else:
            for i in self.shopping_data:
                if i[0] == shopping_id:
                    i[3] = i[3] + shopping_num
                    i[4] = i[4] + shopping_total_price
                    self.__shoppingData()
                    return
            count = [shopping_id, shopping_name, shopping_price, shopping_num, shopping_total_price]
            self.shopping_data.append(count)
            self.__shoppingData()

    # 数据持久化
    def __shoppingData(self):
        df = pd.DataFrame(self.shopping_data)
        df.to_csv(f"./data/{self.username}.csv",sep="\t",header=["商品ID","商品名称","商品单价","商品数量","商品总价"],index=False)

    # 返回购物车数据
    def getShoppingData(self):
        return self.shopping_data
class Shopping:
    user = User()
    shopping = None
    commodity_data = []

    def __init__(self):
        df = pd.read_csv("./data/shopping.csv",sep="\t")
        self.commodity_data = df.values.tolist()

    def __new__(cls, *args, **kwargs):
        if cls.shopping is None:
            cls.shopping = object.__new__(cls)
        return cls.shopping

    # 返回商品列表
    def getShopping(self):
        return self.commodity_data

    # 返回商品ID的列表集合
    def getCommodityDataID(self):
        ID_list = []
        for i in self.commodity_data:
            ID_list.append(i[0])
        return ID_list

    # 返回指定商品的单价
    def getPrice(self,shopping_ID):
        for i in self.commodity_data:
            if i[0] == shopping_ID:
                return i[2]

    # 返回指定商品的名称
    def getName(self,shopping_ID):
        for i in self.commodity_data:
            if i[0] == shopping_ID:
                return i[1]

    # 购买
    def buy(self,username,shopping_id,shopping_num):
        self.username = username
        self.user_shopping_data = UserShoppingData(self.username)
        if shopping_id in self.getCommodityDataID():
            for i in self.commodity_data:
                if i[0] == shopping_id:
                    if i[3] >= shopping_num:
                        if self.user.getPrice(self.username) >= shopping_num * self.getPrice(shopping_id):
                            self.user_shopping_data.addShoppingData(shopping_id,self.getName(shopping_id),self.getPrice(shopping_id),shopping_num,self.getPrice(shopping_id) * shopping_num)
                            self.reduceShopping(shopping_id,shopping_num)
                        else:
                            print("余额不足")
                    else:
                        print(f"库存不足{shopping_num}")
        else:
            print("商品ID不存在")

    # 用于购买商品后减少库存
    def reduceShopping(self,shopping_id,shopping_num):
        for i in self.commodity_data:
            if i[0] == shopping_id:
                i[3] = i[3] - shopping_num
                self.__shopping()

    # 数据持久化
    def __shopping(self):
        df = pd.DataFrame(self.commodity_data)
        df.to_csv("./data/shopping.csv",sep="\t",index=False,header=["商品编号","商品名称","商品单价","商品库存(斤)"])

# 工具类
class Util:
    def loginRegister(self,count):
        if count == 0:
            print("{:*^75}".format("欢迎进入三乐购物系统初始界面"))
        else:
            print("{:*^80}".format(""))
        print("\t\t1.登录")
        print("\t\t2.注册")

    def initialInterface(self,count):
        if count == 0:
            print("{:*^75}".format("欢迎进入三乐购物系统"))
        else:
            print("{:*^80}".format(""))
        print("\t\t1.查看商品")
        print("\t\t2.查看购物车")

    # 购买
    def buy(self):
        print("{:*^80}".format(""))
        print("\t\t1.购买")
        print("\t\t2.返回上一级")

    # 输出商品
    def outputShopping(self):
        spg = Shopping()
        print("{:^10}{:^10}{:^10}{:^10}".format("商品编号","商品名称","商品单价","商品库存(斤)"))
        for i in spg.getShopping():
            print("{:^12}{:^12}{:^12}{:^12}".format(i[0],i[1],i[2],i[3]))

    # 购买业务的实现
    def viewProduct(self):
        while True:
            util.buy()
            buy = input("请输入你的选择:")
            if buy.isdigit():
                buy = int(buy)
                if buy == 1:
                    util.outputShopping()
                    shopping_id = input("请输入你要购买商品的编号:")
                    shopping_num = input("请输入你要购买的数量:")
                    if shopping_id == "quit" or shopping_num == "quit":
                        print("登出~")
                        return "quit"
                    if shopping_id.isdigit() and shopping_num.isdigit():
                        shopping_id = int(shopping_id)
                        shopping_num = int(shopping_num)
                        shopping = Shopping()
                        shopping.buy(perpetual_username, shopping_id, shopping_num)
                    else:
                        print("你的输入有误，请重新输入")
                elif buy == 2:
                    return
                else:
                    print("你输入的有误，请重新输入")
            elif buy == "quit":
                print("登出~")
                return "quit"
            else:
                print("你输入的有误，请重新输入")

    # 显示购物车数据
    def showShoppingDaata(self):
        user_shopping_data = UserShoppingData(perpetual_username)
        print("{:^10}{:^10}{:^10}{:^10}{:^10}".format("商品ID","商品名称","商品单价","商品数量","商品总价"))
        for i in user_shopping_data.getShoppingData():
            print("{:^12}{:^12}{:^12}{:^12}{:^12}".format(i[0],i[1],i[2],i[3],i[4]))

if __name__ == '__main__':
    util = Util()
    count = 0
    # 登录、注册
    while True:
        util.loginRegister(count)
        num = input("请输入你的选择(quit退出):")
        if num.isdigit():
            num = int(num)
            if num == 1:
                perpetual_username = input("请输入用户名:")
                passowrd = input("请输入密码:")
                if perpetual_username == "quit" or passowrd == "quit":
                    print("再见~")
                    sys.exit(0)
                user = User()
                countre = user.login(perpetual_username,passowrd)
                if countre:
                    break
            elif num == 2:
                username = input("请输入用户名:")
                passowrd = input("请输入密码:")
                price = input("请充值初始金额:")
                if price.isdigit():
                    user = User()
                    user.register(username, passowrd, price)
                elif username == "quit" or passowrd == "quit" or price == "quit":
                    print("再见~")
                    sys.exit(0)
                else:
                    print("你输入的有误，请重新输入")
            else:
                print("你输入的有误，请重新输入")
        elif num == "quit":
            print("再见~")
            sys.exit(0)
        else:
            print("输入不合法，请重新输入")
        count +=1

    count = 0
    # 购买业务
    while True:
        util.initialInterface(count)
        num1 = input("请输入你的选择:")
        if num1.isdigit():
            num1 = int(num1)
            if num1 == 1:
                a = util.viewProduct()
                if a == "quit":
                    sys.exit(0)
            elif num1 == 2:
                util.showShoppingDaata()
            else:
                print("你输入的有误，请重新输入")
        elif num1 == "quit":
            print("登出~")
            sys.exit(0)
        else:
            print("你输入的有误，请重新输入")
        count +=1

